define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'vue', 'image', 'hook'], function ($, undefined, Backend, Table, Form, Vue, Image, Hook) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'goods/goods/index' + location.search,
                    add_url: 'goods/goods/add',
                    edit_url: 'goods/goods/edit',
                    del_url: 'goods/goods/del',
                    multi_url: 'goods/goods/multi',
                    import_url: 'goods/goods/import',
                    table: 'goods',
                }
            });

            var table = $("#table");

            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $("input[name='cate_id']", form)
                    .addClass("selectpage")
                    .data("source", "category/index")
                    .data("primaryKey", "id")
                    .data("field", "name")
                    .data("orderBy", "id desc");
                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                fixedColumns: true,
                fixedRightNumber: 1,
                search: false,
                commonSearch: true,
                searchFormVisible: true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'cate_id', title: __('Cate_id'), visible:false, operate: 'LIKE %...%'},
                        {field: 'category.name', title: __('Cate_id'), operate: false},
                        {field: 'goods_sn', title: __('Goods_sn'), operate: 'LIKE'},
                        {field: 'goods_name', title: __('Goods_name'), operate: 'LIKE'},
                        {field: 'brand', title: __('Brand'), operate: 'LIKE'},
                        {field: 'status', title: __('Status'), searchList: {"up":__('Status up'),"hidden":__('Status hidden'),"down":__('Status down')}, formatter: Table.api.formatter.status},
                        {field: 'weigh', title: __('Weigh'), operate: false},
                        {field: 'image', title: __('Image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'images', title: __('Images'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.images},
                        {field: 'params', title: __('Params'), operate: 'LIKE'},
                        {field: 'price', title: __('Price'), operate:'BETWEEN'},
                        {field: 'original_price', title: __('Original_price'), operate:'BETWEEN'},
                        {field: 'limit_num', title: __('Limit_num')},
                        {field: 'stock_type', title: __('Stock_type'), searchList: {"place":__('Stock_type place'),"pay":__('Stock_type pay')}, formatter: Table.api.formatter.normal},
                        {field: 'service_ids', title: __('Service_ids'), operate: 'LIKE'},
                        {field: 'dispatch_type', title: __('Dispatch_type'), searchList: {"express":__('Dispatch_type express')}, operate:'FIND_IN_SET', formatter: Table.api.formatter.label},
                        {field: 'dispatch_ids', title: __('Dispatch_ids'), operate: 'LIKE'},
                        {field: 'likes', title: __('Likes')},
                        {field: 'views', title: __('Views')},
                        {field: 'sales', title: __('Sales')},
                        {field: 'show_sales', title: __('Show_sales')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'goods/goods/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'goods/goods/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'goods/goods/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
            var vm = new Vue({
                el: '#app',
                data() {
                    return {
                        attrGroups: [],
                        attrItems: [],
                        productSkus: [],
                        skus: []
                    }
                },
                computed: {
                    productSkusStr() {
                        return JSON.stringify(this.productSkus)
                    }
                },
                mounted() {
                    Image.init()
                },
                methods: {
                    setAttrGroupName(i, e) {
                        this.$set(this.attrGroups, i, e.target.value)
                    },
                    addRow() {
                        var val = this.$refs['attr-group-name'].value
                        if ($.trim(val) == '') {
                            Toastr.error("不能为空")
                            return
                        }
                        if (val.indexOf(',') > -1) {
                            Toastr.error("规格子项 " + val + " 不能包含符号‘,’")
                            return
                        }
                        this.attrGroups.push(val)
                        this.$refs['attr-group-name'].value = ''
                    },
                    addChild(index) {
                        var val = this.$refs['attr-item-name-' + index][0].value
                        // if ($.trim(val) == '') {
                        //     Toastr.error("不能为空")
                        //     return
                        // }
                        if (val.indexOf(',') > -1) {
                            Toastr.error("规格 " + val + " 不能包含符号‘,’")
                            return
                        }
                        if (!val) return false
                        if (this.attrItems[index]) {
                            this.attrItems[index].push(val)
                        } else {
                            this.attrItems.push([val])
                        }
                        this.$refs['attr-item-name-' + index][0].value = ""
                        this.generateProducts()
                    },
                    upimage(i) {
                        Image.open(function(data) {
                            $('#c-attr-image-' + i).val(data.url)
                            if (vm.skus[i]) {
                                vm.$set(vm.skus[i], 'image', data.url)
                            } else {
                                vm.$set(vm.skus, i, {image: data.url})
                            }
                            Image.close()
                        })
                    },
                    removeChild(i, j) {
                        this.attrItems[i].pop(j)
                        this.generateProducts()
                    },
                    removeGroup(i) {
                        this.attrGroups.pop(i)
                        if (this.attrItems[i])
                            this.attrItems.pop(i)
                        this.generateProducts()
                    },
                    generateProducts() {
                        this.productSkus = this.descartes(this.attrItems)
                    },
                    descartes(array){
                        if (array.length == 0) return []
                        if( array.length < 2 ) {
                            var res = []
                            array[0].forEach(function(v) {
                                res.push([v])
                            })
                            return res
                        }
                        return [].reduce.call(array, function(col, set) {
                            var res = [];
                            col.forEach(function(c) {
                                set.forEach(function(s) {
                                    var t = [].concat( Array.isArray(c) ? c : [c] );
                                    t.push(s);
                                    res.push(t);
                                })});
                            return res;
                        });
                    }
                }
            })
            Controller.api.bindevent();

            window.batchSetAttrs = function(field) {
                $('.attr-' + field).val($('#batch-' + field).val())
            }
            Hook.listen('document')
        },
        edit: function () {
            // ajaxGetSpecInput();
            Controller.api.bindevent();

            var vm = new Vue({
                el: '#app',
                data() {
                    return {
                        attrGroups: [],
                        attrItems: [],
                        productSkus: [],
                        skus: []
                    }
                },
                computed: {
                    productSkusStr() {
                        return JSON.stringify(this.productSkus)
                    }
                },
                mounted() {
                    skus = JSON.parse(skus)
                    if (skus.length) {
                        this.skus = skus
                        this.attrGroups = this.skus[0].keys.split(',')
                        this.attrItems = JSON.parse(attrItems);
                        this.generateProducts()
                    }
                    Image.init()
                },
                methods: {
                    setAttrGroupName(i, e) {
                        this.$set(this.attrGroups, i, e.target.value)
                    },
                    addRow() {
                        var val = this.$refs['attr-group-name'].value
                        // if ($.trim(val) == '') {
                        //     Toastr.error("不能为空")
                        //     return
                        // }
                        if (val.indexOf(',') > -1) {
                            Toastr.error("规格 " + val + " 不能包含符号‘,’")
                            return
                        }
                        this.attrGroups.push(val)
                        this.$refs['attr-group-name'].value = ''
                    },
                    addChild(index) {
                        var val = this.$refs['attr-item-name-' + index][0].value
                        // if ($.trim(val) == '') {
                        //     Toastr.error("不能为空")
                        //     return
                        // }
                        if (val.indexOf(',') > -1) {
                            Toastr.error("规格子项 " + val + " 不能包含符号‘,’")
                            return
                        }
                        if (!val) return false
                        if (this.attrItems[index]) {
                            this.attrItems[index].push(val)
                        } else {
                            this.attrItems.push([val])
                        }
                        this.$refs['attr-item-name-' + index][0].value = ""
                        this.generateProducts()
                    },
                    upimage(i) {
                        Image.open(function(data) {
                            $('#c-attr-image-' + i).val(data.url)
                            if (vm.skus[i]) {
                                vm.$set(vm.skus[i], 'image', data.url)
                            } else {
                                vm.$set(vm.skus, i, {image: data.url})
                            }
                            Image.close()
                        })
                    },
                    removeChild(i, j) {
                        this.attrItems[i].pop(j)
                        this.generateProducts()
                    },
                    removeGroup(i) {
                        this.attrGroups.pop(i)
                        this.attrItems.pop(i)
                        this.generateProducts()
                    },
                    batchSetAttr($type) {
                        for(var i = 0; i < this.skus.length; i ++) {
                            this.$set(this.skus[i], $type, this.$refs['input-' + $type].value)
                        }
                    },
                    generateProducts() {
                        this.productSkus = this.descartes(this.attrItems)
                    },
                    descartes(array){
                        if (array.length == 0) return []
                        if( array.length < 2 ) {
                            var res = []
                            array[0].forEach(function(v) {
                                res.push([v])
                            })
                            return res
                        }
                        return [].reduce.call(array, function(col, set) {
                            var res = [];
                            col.forEach(function(c) {
                                set.forEach(function(s) {
                                    var t = [].concat( Array.isArray(c) ? c : [c] );
                                    t.push(s);
                                    res.push(t);
                                })});
                            return res;
                        });
                    }
                }
            })
            window.batchSetAttr = function(field) {
                $('.attr-' + field).val($('#batch-' + field).val())
            }
            Hook.listen('form')
        },
        api: {
            bindevent: function () {

                // $(function () {
                //     $(document).on("click", '.delete_item', function (e) {
                //         if ($(this).text() == '禁用') {
                //             // $(this).parent().parent().find('input').removeAttr('disabled');
                //             $(this).next().val(0);
                //             $(this).addClass('btn-info');
                //             $(this).removeClass('btn-danger');
                //             $(this).text('启用');
                //         } else {
                //             $(this).next().val(1);
                //             $(this).addClass('btn-danger');
                //             $(this).removeClass('btn-info');
                //             $(this).text('禁用');
                //             // $(this).parent().parent().find('input').attr('disabled', 'disabled');
                //         }
                //         console.log($(this).next().val())
                //     })
                //     // 规格按钮切换 class
                //     $(".spec").click(function(){
                //         console.log(123)
                //         if($(this).hasClass('btn-success'))
                //         {
                //             $(this).removeClass('btn-success');
                //             $(this).addClass('btn-default');
                //         }else{
                //             $(this).removeClass('btn-default');
                //             $(this).addClass('btn-success');
                //         }
                //         ajaxGetSpecInput();
                //     });
                // })
                //
                // /**
                //  *  点击商品规格触发下面输入框显示
                //  */
                // function ajaxGetSpecInput() {
                //     var spec_arr = {};// 用户选择的规格数组
                //     // 选中了哪些属性
                //     $("#goods_spec_table1  button").each(function () {
                //         if ($(this).hasClass('btn-success')) {
                //             var spec_id = $(this).data('spec_id');
                //             var item_id = $(this).data('item_id');
                //             if (!spec_arr.hasOwnProperty(spec_id))
                //                 spec_arr[spec_id] = [];
                //             spec_arr[spec_id].push(item_id);
                //         }
                //     });
                //
                //     ajaxGetSpecInput2(spec_arr); // 显示下面的输入框
                // }
                //
                // /**
                //  * 根据用户选择的不同规格选项
                //  * 返回 不同的输入框选项
                //  */
                // function ajaxGetSpecInput2(spec_arr) {
                //
                //     var goods_id = $("input[name='goods_id']").val();
                //     $.ajax({
                //         type: 'POST',
                //         data: {spec_arr: spec_arr, goods_id: goods_id},
                //         url: "goods/goods/ajaxGetSpecInput",
                //         success: function (data) {
                //             $("#goods_spec_table2").html('').append(data);
                //
                //             hbdyg();  // 合并单元格
                //
                //             // Controller.api.bindevent();
                //         }
                //     });
                //
                // }
                //
                // // 合并单元格
                // function hbdyg() {
                //     var tab = document.getElementById("spec_input_tab"); //要合并的tableID
                //     var maxCol = 2, val, count, start;  //maxCol：合并单元格作用到多少列
                //     if (tab != null) {
                //         for (var col = maxCol - 1; col >= 0; col--) {
                //             count = 1;
                //             val = "";
                //             for (var i = 0; i < tab.rows.length; i++) {
                //                 if (val == tab.rows[i].cells[col].innerHTML) {
                //                     count++;
                //                 } else {
                //                     if (count > 1) { //合并
                //                         start = i - count;
                //                         tab.rows[start].cells[col].rowSpan = count;
                //                         for (var j = start + 1; j < i; j++) {
                //                             tab.rows[j].cells[col].style.display = "none";
                //                         }
                //                         count = 1;
                //                     }
                //                     val = tab.rows[i].cells[col].innerHTML;
                //                 }
                //             }
                //             if (count > 1) { //合并，最后几行相同的情况下
                //                 start = i - count;
                //                 tab.rows[start].cells[col].rowSpan = count;
                //                 for (var j = start + 1; j < i; j++) {
                //                     tab.rows[j].cells[col].style.display = "none";
                //                 }
                //             }
                //         }
                //     }
                // }

                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
